import React, { Component, Fragment } from 'react';
import { Cascader } from 'antd';
import { reqGet } from '@/helpers/request';
import apiConfig from '@/apiConfig';
import map from 'lodash/map';
import isFunction from 'lodash/isFunction';
import isEmpty from 'lodash/isEmpty';

const limit = {
  maxLevel: 4,
};

export default class SelectArea extends Component {
  // 返回一个对象来更新 state
  static getDerivedStateFromProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {}),
      };
    }
    return null;
  }

  constructor(props) {
    super(props);
    const value = props.value || {};
    this.state = {
      options: props.options || [],
      country: value.country || '',
      province: value.province || '',
      city: value.city || '',
      area: value.area || '',
      village: value.village || '',
      compUpdate: Math.ceil(Math.random() * 100),
    };
  }

  componentDidMount() {
    this.fetchAddress();
  }

  //type:{1:国家,2:省,3:市,4:区/镇,5:乡}
  fetchAddress = (parent = 0, type = 1, callback = '', targetOption) => {
    reqGet(apiConfig.findAddress, { parent: parent, type: type }).then(rsp => {
      if (rsp && (200 == rsp.status || 1 == rsp.status)) {
        let temp = [];
        map(rsp.data, (o) => {
          temp.push({
            valId: o.id,
            label: o.name,
            value: o.name,
            type: type,
            isLeaf: false,
          });
        });
        if (parent == 0) {
          this.setState({ options: temp });
        } else {

          isFunction(callback) && callback(temp);
        }
      }
    });
  };

  handleChange(value) {
    console.log('value:', value);
    const nextState = {
      country: value[0],
      province: value[1],
      city: value[2],
      area: value[3],
    };

    if (!('value' in this.props)) {
      this.setState(nextState);
    }
    this.triggerChange(nextState);
  }

  triggerChange = (changedValue) => {
    // Should provide an event to pass value to Form.
    const onChange = this.props.onChange;
    if (onChange) {
      onChange({ ...this.state, ...changedValue });
    }
  };

  loadData = (selectedOptions) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    if (limit['maxLevel'] == targetOption.type) {
      return false;
    }
    if (isEmpty(targetOption.children)) {
      targetOption.loading = true;
      this.fetchAddress(targetOption.valId, (targetOption.type + 1), (data) => {
        targetOption.loading = false;
        targetOption.children = data;
        this.setState({
          compUpdate: Math.ceil(Math.random() * 100),
        });
      });
    }
  };

  render() {
    //const options = [
    //  {
    //    value: 'zhejiang',
    //    label: 'Zhejiang',
    //    children: [
    //      {
    //        value: 'hangzhou',
    //        label: 'Hangzhou',
    //        children: [
    //          {
    //            value: 'xihu',
    //            label: 'West Lake',
    //          },
    //        ],
    //      },
    //    ],
    //  },
    //  {
    //    value: 'jiangsu',
    //    label: 'Jiangsu',
    //    children: [
    //      {
    //        value: 'nanjing',
    //        label: 'Nanjing',
    //        children: [
    //          {
    //            value: 'zhonghuamen',
    //            label: 'Zhong Hua Men',
    //          },
    //        ],
    //      },
    //    ],
    //  },
    //];
    //  {/*value={values(this.state)}*/}
    const { options } = this.state;
    const value = [];

    if (this.state.country) value.push(this.state.country);
    if (this.state.province) value.push(this.state.province);
    if (this.state.city) value.push(this.state.city);
    if (this.state.area) value.push(this.state.area);

    return (
      <Fragment>
        <Cascader
          value={value}
          size={this.props.size || ''}
          options={options}
          loadData={this.loadData}
          changeOnSelect={true}
          onChange={this.handleChange.bind(this)}
          placeholder="请选择所在地"
        />
      </Fragment>
    );
  }
}
